<template>
  <div class="x-code-judge">
    <div class="code-mirror">
      <x-code-mirror
         ref="codeMirror"
         :language-list="languageList"
      />
      <div :class="[{'open' : open}]" class="judge-drawer">
        <a-card
            size="small"
            style="width: 100%;height: 100%;border-radius: 5px 5px 0 0"
            :tab-list="tabListNoTitle"
            :active-tab-key="noTitleKey"
            @tabChange="key => onTabChange(key, 'noTitleKey')"
        >
          <div v-if="noTitleKey === 'input'">
            <a-tabs size="small" type="editable-card" v-model:activeKey="checkTestCase"  @edit="onEdit">
              <a-tab-pane v-for="(pane,index) in testCases" :key="index" :tab="'case'+(index+1)" :closable="true">
                <a-form layout="vertical">
                  <a-form-item label="输入">
                    <a-textarea :rows="5" v-model:value="pane.input" placeholder="textarea with clear icon" allow-clear />
                  </a-form-item>
                  <a-form-item label="预期输出">
                    <a-textarea :rows="5" v-model:value="pane.output" placeholder="textarea with clear icon" allow-clear />
                  </a-form-item>
                </a-form>
              </a-tab-pane>
            </a-tabs>
           </div>
          <div v-else>
            <a-alert
                :message="getTypeByStatus(testStatus.status).name"
                :description="testStatus.msg"
                :type="getTypeByStatus(testStatus.status).type"
                show-icon
            />
            <a-form v-if="testStatus.file" style="margin-top: 5px" layout="vertical">
              <a-form-item label="运行结果">
                <a-textarea :rows="5" v-model:value="testStatus.file" placeholder="textarea with clear icon" allow-clear />
              </a-form-item>
              <a-form-item label="预期输出">
                <a-textarea :rows="5" v-model:value="testStatus.expectedOutput" placeholder="textarea with clear icon" allow-clear />
              </a-form-item>
            </a-form>
          </div>
          <template v-if="user.isLogin" #tabBarExtraContent>
            <a @click="toSubmitTest">运行测试</a>
          </template>
          <template v-else #tabBarExtraContent>
            <a @click="gotoLogin">登录后提交</a>
          </template>
        </a-card>
      </div>
    </div>
    <div :style="{backgroundColor : token.colorBgContainer}" class="judge-footer">
      <div class="btns">
        <a-button @click="openDrawer" type="primary">
          {{open ? "隐藏" : "测试"}}
        </a-button>
        <a-button  :disabled="!user.isLogin || lastSubmit > 0"  @click="toSubmitProblem">
          <span>提交</span>
          <span v-if="lastSubmit > 0">
            {{lastSubmit}}
          </span>
        </a-button>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import {getTypeByStatus} from '@/common/enum';
import XCodeMirror from "@/components/XCodeMirror/index.vue";
import useStore from "@/store";
const {user,webConfig} = useStore()
import {onMounted, reactive, ref} from 'vue';
const lang = ref("cpp")
const open = ref(false);
const props =  defineProps({
  problemId : {
    default: '0'
  },
  contestId : {
    default: '0'
  },
  judgeList:{
    type : Array as () => JudgeResult[],
    required : true,
    default:() => []
  },
  testCaseList:{
    type : Array as () => TestCase[],
    required : false,
    default:() => []
  },
  languageList:{
    type: Object as () => Map<string,Object>,
    default:() => ({})
  }
})
type TestCase = {
  input:string,
  output:string,
}
const checkTestCase= ref<Number>(0);
const testCases = reactive<Array<TestCase>>([
])
const testStatus = reactive<RunResult>({
  status: 15
})
const judgeList = reactive<Array<JudgeResult>>([]);
let judge: IJudge;
onMounted(()=>{
  judge = new Judge(testStatus,props.judgeList as Array<JudgeResult>);
  if(props.testCaseList != null && props.testCaseList.length > 0){
    testCases.push(...props.testCaseList)
  }else {
    checkTestCase.value = -1;
    add();
  }
})
const emit = defineEmits(
["addJudge"]
)
const openDrawer = () =>{
  if(open.value)
    open.value = false;
  else
    open.value = true;
}
const tabListNoTitle = [
  {
    key: 'input',
    tab: '测试用例',
  },
  {
    key: 'result',
    tab: '执行结果',
  }
];
const key = ref('input');
const noTitleKey = ref('input');
const onTabChange = (value: string, type: string) => {
  //console.log(value, type);
  if (type === 'key') {
    key.value = value;
  } else if (type === 'noTitleKey') {
    noTitleKey.value = value;
  }
};
import { theme } from 'ant-design-vue';
import languagesMap, {Judge,IJudge} from "@/components/XCodeJudge/judge";
import type {JudgeResult, RunResult} from "@/api/judge";
const { useToken } = theme;
const { token } = useToken();
const lastSubmit = ref(0)
const codeMirror = ref(null)
const toSubmitTest =  async () => {
  const info = codeMirror.value.getCodeMirrorInfo();
  const data = {
    pid: props.problemId,
    code: info.code,
    language: info.lang,
    testCaseInput: testCases[checkTestCase.value].input,
    expectedOutput: testCases[checkTestCase.value].output,
  }
  testStatus.testCaseInput = data.testCaseInput
  testStatus.expectedOutput = data.expectedOutput
  noTitleKey.value = "result"
  judge.submitProblemTest(data)
}
const toSubmitProblem = async () => {

  lastSubmit.value = 6
  const t = setInterval(()=>{
    --lastSubmit.value;
   // console.log("666")
    if(lastSubmit.value <= 0){
      clearInterval(t);
    }
  },1000)
  const info = codeMirror.value.getCodeMirrorInfo();
  const data = {
    pid: props.problemId,
    code: info.code,
    language: info.lang,
    cid : props.contestId
  }
  const res = await judge.submitJudgeProblem(data);
  emit('addJudge',res);

}

const add = () => {
  testCases.push({
    input:"",
    output:""
  });
  //console.log(checkTestCase.value)
  checkTestCase.value = checkTestCase.value + 1
};

const remove = (targetKey: Number) => {
  let lastIndex = targetKey - 1;

  testCases.splice(targetKey,1);

  if (testCases.length && checkTestCase.value === targetKey) {
    if (lastIndex >= 0) {
      checkTestCase.value = lastIndex;
    } else {
      checkTestCase.value = 0
    }
  }
};
const gotoLogin = () => {
  webConfig.loginOpr();
}
const onEdit = (targetKey: Number | MouseEvent, action: string) => {
  //console.log(targetKey)
  if (action === 'add') {
    add();
  } else {
    remove(targetKey as Number);
  }
};
</script>

<style lang="scss" scoped>
@import "src/assets/base";
.x-code-judge{
  height: 100%;
  display: flex;
  flex-direction: column;
  .code-mirror{
    position: relative;
    flex: 1;
    overflow-y: hidden;
    .judge-drawer{
      width: 100%;
      position: absolute;
      bottom: 0;
      height: 0;
      z-index: 0;
      transition: height .5s;
      overflow: hidden;
      @include a-card-flex;

    }
    .open{
      height: 70%;
    }
  }
  .judge-footer{
    width: 100%;
    .btns{
      display: flex;
      justify-content: end;
      padding: 10px;
      button:first-child{
        margin-right: 10px;
      }
    }

    z-index: 1;
  }

}
</style>
